package com.kgcx.common.handler;

import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.kgcx.common.bean.ReturnData;
import com.kgcx.common.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.UnsatisfiedServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.multipart.MultipartException;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class GlobalExceptionHandler {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ReturnData defaultErrorHandler(HttpServletRequest req, Exception e) {
        String code = "-1";
        String msg = "内部错误," + e.getMessage();
        if (e instanceof MissingServletRequestParameterException) {
            msg = "参数为空！" + ((MissingServletRequestParameterException) e).getParameterName();
        } else if (e instanceof MissingPathVariableException) {
            msg = "参数为空！" + ((MissingPathVariableException) e).getVariableName();
        } else if (e instanceof UnsatisfiedServletRequestParameterException) {
            UnsatisfiedServletRequestParameterException ex = (UnsatisfiedServletRequestParameterException) e;
            msg = "参数类型或长度错误！" + ex.getActualParams() + ",约束：" + ex.getMessage();
        } else if (e instanceof MethodArgumentTypeMismatchException) {
            MethodArgumentTypeMismatchException ex = (MethodArgumentTypeMismatchException) e;
            msg = "参数类型或长度错误！" + ex.getName() + ",约束：" + ex.getParameter().getParameter().getType().getSimpleName();
        } else if (e instanceof MultipartException) {
            msg = "上传文件异常！";
        } else if (e instanceof InvalidFormatException) {
            InvalidFormatException ex = (InvalidFormatException) e;
            msg = "参数错误！约束:" + ex.getValue();
        } else if (e instanceof BusinessException) {
            BusinessException ex = (BusinessException) e;
            code = ex.getCode();
            msg = ex.getMessage();
        }
        ReturnData returnData = new ReturnData(code, msg);
        log.error(returnData.toString(), e);
        return returnData;
    }
}